package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.wages.domain.GzEmployeeEvaluation;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.req.GzEmployeeEvaluationAdd;
import com.gpframework.module.wages.domain.req.GzEmployeeEvaluationReq;
import com.gpframework.module.wages.domain.req.GzEmployeeEvaluationUpdate;
import com.gpframework.module.wages.domain.req.GzGenerateReq;
import com.gpframework.module.wages.domain.vo.GzEmployeeEvaluationVo;
import com.gpframework.module.wages.service.IGzEmployeeEvaluationService;
import com.gpframework.module.wages.service.IGzPersonnelFoundationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * @ClassName GzEmployeeEvaluationController
 * @Author gpframework
 * @Date 2024-01-19
 * @Version 1.0.0
 * @Description 员工评定Controller
 */
@Validated
@Api(tags = "员工评定")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/employeeevaluation" )
public class GzEmployeeEvaluationController extends BaseController {

    private final IGzEmployeeEvaluationService iGzEmployeeEvaluationService;
    private final IGzPersonnelFoundationService iGzPersonnelFoundationService;
 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-01-19
  * @Param gzEmployeeEvaluation
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    //@PreAuthorize("@ss.hasPermi('wages:employeeevaluation:list')")
    @GetMapping("/list")
    public TableDataInfo<GzEmployeeEvaluationVo> list(GzEmployeeEvaluationReq gzEmployeeEvaluationReq)
    {
        startPage();
        QueryWrapper<GzEmployeeEvaluation> lqw = new QueryWrapper<GzEmployeeEvaluation>();
        gzEmployeeEvaluationReq.generatorQuery(lqw,true);
        lqw.isNotNull("evaluation_criteria_bonus");
        List<GzEmployeeEvaluationVo> list = iGzEmployeeEvaluationService.listVo(lqw);
        return getDataTable(list);
    }


    @ApiOperation("汇总")
    //@PreAuthorize("@ss.hasPermi('wages:employeeevaluation:list')")
    @GetMapping("/listed")
    public TableDataInfo<GzEmployeeEvaluationVo> listed(GzEmployeeEvaluationReq gzEmployeeEvaluationReq)
    {
        startPage();
        QueryWrapper<GzEmployeeEvaluation> lqw = new QueryWrapper<GzEmployeeEvaluation>();
        gzEmployeeEvaluationReq.generatorQuery(lqw,true);
        lqw.isNotNull("evaluation_criteria_bonus");
        List<GzEmployeeEvaluationVo> list = iGzEmployeeEvaluationService.listVoed(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzEmployeeEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    //@PreAuthorize("@ss.hasPermi('wages:employeeevaluation:add')" )
    @Log(title = "添加员工评定" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzEmployeeEvaluationAdd gzEmployeeEvaluationAdd) {
        GzEmployeeEvaluation gzEmployeeEvaluation = Convert.convert(new TypeReference<GzEmployeeEvaluation>() {}, gzEmployeeEvaluationAdd);
        return toAjax(iGzEmployeeEvaluationService.save(gzEmployeeEvaluation) ? 1 : 0);
    }


    @ApiOperation("生成员工评定")
    //@PreAuthorize("@ss.hasPermi('wages:employeeevaluation:generateEvaluate')" )
    @Log(title = "生成员工评定" , businessType = BusinessType.INSERT)
    @PostMapping("/generateEvaluate")
    public AjaxResult generateEvaluate(@RequestBody GzGenerateReq gzGenerateReq) throws ParseException {
        List<GzPersonnelFoundation> gzPersonnelFoundations=iGzPersonnelFoundationService.lambdaQuery().ne(GzPersonnelFoundation::getDepartmentType,3)
                .list();
        iGzEmployeeEvaluationService.deleteByMonth(gzGenerateReq.getYearMonth());
        List<GzEmployeeEvaluation> gzEmployeeEvaluations=new ArrayList<>();
        for (GzPersonnelFoundation gzPersonnelFoundation : gzPersonnelFoundations){
            GzEmployeeEvaluation gzEmployeeEvaluation=new GzEmployeeEvaluation();
            gzEmployeeEvaluation.setMonth(gzGenerateReq.getYearMonth());
            gzEmployeeEvaluation.setDepartmentName(gzPersonnelFoundation.getDepartmentName());
            gzEmployeeEvaluation.setUserId(gzPersonnelFoundation.getId());
            gzEmployeeEvaluation.setName(gzPersonnelFoundation.getName());
            gzEmployeeEvaluation.setEvaluationCriteriaBonus(gzPersonnelFoundation.getEvaluationCriteriaBonus());
            gzEmployeeEvaluations.add(gzEmployeeEvaluation);
        }

        return AjaxResult.success( iGzEmployeeEvaluationService.saveBatch(gzEmployeeEvaluations)?1:0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzEmployeeEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    //@PreAuthorize("@ss.hasPermi('wages:employeeevaluation:edit')" )
    @Log(title = "修改员工评定" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody GzEmployeeEvaluationUpdate gzEmployeeEvaluationUpdate) {
        List<GzEmployeeEvaluation> convert = Convert.convert(new TypeReference<List<GzEmployeeEvaluation>>() {
        }, gzEmployeeEvaluationUpdate.getGzEmployeeEvaluationAddList());
        return toAjax(iGzEmployeeEvaluationService.updateBatchById(convert) ? 1 : 0);
    }


    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzEmployeeEvaluation
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('wages:employeeevaluation:export')" )
    @Log(title = "导出员工评定" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzEmployeeEvaluationReq gzEmployeeEvaluationReq) {
        QueryWrapper<GzEmployeeEvaluation> lqw = new QueryWrapper<GzEmployeeEvaluation>();
        gzEmployeeEvaluationReq.generatorQuery(lqw,true);
        lqw.isNotNull("evaluation_criteria_bonus");
        List<GzEmployeeEvaluationVo> list = iGzEmployeeEvaluationService.listVo(lqw);
        ExcelUtil<GzEmployeeEvaluationVo> util = new ExcelUtil<GzEmployeeEvaluationVo>(GzEmployeeEvaluationVo. class);
        return util.exportExcel(list, "employeeevaluation" );
    }


    @ApiOperation("下载员工评定模板")
    @Log(title = "下载员工评定模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate" )
    public AjaxResult importTemplateOfficeclerks() {
        ExcelUtil<GzEmployeeEvaluationVo> util = new ExcelUtil<GzEmployeeEvaluationVo>(GzEmployeeEvaluationVo.class);
        return util.importTemplateExcel("员工评定模板");
    }


    @ApiOperation("导入员工评定有提示")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "导入员工评定有提示", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importListNote(MultipartFile file, boolean updateSupport) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

        // 导入新数据
        ExcelUtil<GzEmployeeEvaluationVo> util = new ExcelUtil<GzEmployeeEvaluationVo>(GzEmployeeEvaluationVo.class);
        List<GzEmployeeEvaluationVo> excelList = util.importCacheExcel(file.getInputStream());

        String message = iGzEmployeeEvaluationService.importListNote(excelList, updateSupport);
        return AjaxResult.success(message);
    }







    @ApiOperation("导入")
    //@PreAuthorize("@ss.hasPermi('manufacture:employeeevaluation:add')" )
    @Log(title = "导入" , businessType = BusinessType.INSERT)
    //@PostMapping("/import")
    @Transactional
    public AjaxResult importList(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }
         // 导入新数据
        ExcelUtil<GzEmployeeEvaluationVo> util = new ExcelUtil<GzEmployeeEvaluationVo>(GzEmployeeEvaluationVo.class);
        List<GzEmployeeEvaluationVo> excelList = util.importCacheExcel(file.getInputStream());
        List<GzEmployeeEvaluation> list = Convert.convert(new TypeReference<List<GzEmployeeEvaluation>>() {}, excelList);

       for (int i = 0; i < list.size(); i++) {
           GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                   .eq("name", list.get(i).getName())
                   .eq("department_name", list.get(i).getDepartmentName())
                   .eq("del_status", YesNoEnum.NO.getKey()));


           GzEmployeeEvaluation gzEmployeeEvaluation = iGzEmployeeEvaluationService.getOne(new QueryWrapper<GzEmployeeEvaluation>()
                   .eq("name", list.get(i).getName())
                   .eq("department_name", list.get(i).getDepartmentName())
                   .eq("month", list.get(i).getMonth())
                   .eq("del_status", YesNoEnum.NO.getKey()));
           if (!StringUtils.isEmpty(gzEmployeeEvaluation))
           {
               list.get(i).setId(gzEmployeeEvaluation.getId());
           }

           list.get(i).setUserId(gzPersonnelFoundation.getId());
        }

        return iGzEmployeeEvaluationService.saveOrUpdateBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzEmployeeEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('wages:employeeevaluation:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzEmployeeEvaluationVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzEmployeeEvaluationService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzEmployeeEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('wages:employeeevaluation:remove')" )
    @Log(title = "删除员工评定" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzEmployeeEvaluationService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


}
